import { createVNode, render } from 'vue'
import MessageComponent from '@/components/Message.vue'

let messageInstance = null

const Message = {
  success(content, duration) {
    this.show({ content, type: 'success', duration })
  },
  warning(content, duration) {
    this.show({ content, type: 'warning', duration })
  },
  error(content, duration) {
    this.show({ content, type: 'error', duration })
  },
  info(content, duration) {
    this.show({ content, type: 'info', duration })
  },
  show(options) {
    // 如果已存在实例，先移除
    if (messageInstance) {
      messageInstance.component.ctx.hide()
      setTimeout(() => {
        if (messageInstance?.container && document.body.contains(messageInstance.container)) {
          document.body.removeChild(messageInstance.container)
        }
      }, 300) // 等待动画结束
    }

    // 创建容器
    const container = document.createElement('div')
    document.body.appendChild(container)

    // 创建虚拟节点
    const vnode = createVNode(MessageComponent)

    // 渲染组件
    render(vnode, container)

    // 保存实例
    messageInstance = {
      vnode,
      component: vnode.component,
      container
    }

    // 显示消息
    messageInstance.component.ctx.show(options)

    // 消息结束后清理DOM
    const duration = options.duration || 3000
    setTimeout(() => {
      if (messageInstance?.container && document.body.contains(messageInstance.container)) {
        render(null, messageInstance.container)
        document.body.removeChild(messageInstance.container)
        messageInstance = null
      }
    }, duration + 300) // 等待动画结束再移除
  }
}

export default {
  install(app) {
    app.config.globalProperties.$message = Message
  }
}
